package site.marqstree.kotlin.library.good.ui.activity.goodlist

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import kotlinx.android.synthetic.main.fragment_good_list.*
import org.jetbrains.anko.toast
import site.marqstree.kotlin.library.base.extent.onClick
import site.marqstree.kotlin.library.base.ui.activity.BaseMvpActivity
import site.marqstree.kotlin.library.good.R
import site.marqstree.kotlin.library.good.ui.fragment.category.centent.recyclerview.GoodListAdapter
import site.marqstree.kotlin.library.good.ui.activity.goodlist.bean.GoodPageBean
import site.marqstree.kotlin.library.good.ui.activity.goodlist.inject.DaggerGoodListComponent
import site.marqstree.kotlin.library.good.ui.activity.goodlist.presenter.GoodListPresenter
import site.marqstree.kotlin.library.good.ui.activity.goodlist.recyclerview.PageInfo
import site.marqstree.kotlin.library.good.ui.activity.goodlist.view.GoodListView

/*
 * 项目名: KotlinMall
 * 包名: site.marqstree.kotlin.library.good.ui.fragment.goodlist
 * 文件名: FragmentGoodList
 * 创建者: marqstree
 * 创建时间: 2020/3/8 9:18
 * 描述: TODO
 */
class ActivityGoodList:BaseMvpActivity<GoodListPresenter>(),
    GoodListView {

    companion object{
        //品牌id模式
        const val MODE_BRANDID = 1
        //搜索关键字模式
        const val MODE_SEARCH_KEYWORD = 2
    }

    var mMode = MODE_BRANDID
    var mBrandId = -1
        set(value){
            field = value
            refresh()
        }
        get(){
            return field
        }
    var mSearchKeyword = ""
        set(value){
            field = value
            refresh()
        }
        get(){
            return field
        }


    private val mPageInfo = PageInfo()
    private val mAdapter:GoodListAdapter = GoodListAdapter(mutableListOf())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_good_list)

        mMode = intent.getIntExtra("mode",MODE_BRANDID)
        if(mMode==MODE_BRANDID)
            mBrandId = intent.getIntExtra("brandid",0)
        if(mMode== MODE_SEARCH_KEYWORD)
            mSearchKeyword = intent.getStringExtra("serachkeyword")

        //初始化recyclerview
        initRecyclerView()
        //初始化headbar
        initHeadBar()
        //初始化下拉刷新布局
        initRefreshLayout()
        //初始化页脚设置
        initLoadMore()
        // 进入页面，刷新数据
        mSwipeLayout.setRefreshing(true)
        refresh()
    }

    //初始化recyclerview
    private fun initRecyclerView() {
        val manager = GridLayoutManager(this,2)
        mRvGoodList.layoutManager=manager
        mRvGoodList.adapter = mAdapter
        mAdapter.setOnItemClickListener(object: OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                ARouter.getInstance()
                    .build("/good/activity/gooddetail")
                    .withInt("id", mAdapter.data.get(position).id)
                    .navigation()
            }
        })
    }

    //初始化下拉刷新布局
    private fun initRefreshLayout() {
        //设置下拉刷新进度条颜色
        mSwipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189))
        //设置下拉刷新事件
        mSwipeLayout.setOnRefreshListener(OnRefreshListener { //重置数据
            refresh()
        })
    }

    private fun initHeadBar(){
        mHeaderBar.getLeftView().onClick {
            finish()
        }
    }

    /**
     * 初始化页脚设置
     */
    private fun initLoadMore() {
        //初始化页脚点击事件
        mAdapter.loadMoreModule?.setOnLoadMoreListener {  //点击页脚时，追加数据
            loadMore()
        }
        // 开启上拉加载下一页数据（默认为true）
        //关闭时，需点击页脚，才能加载下一页数据
        mAdapter.loadMoreModule?.isAutoLoadMore = true
        //当自动加载开启，同时数据不满一屏时，不允许继续执行自动加载更多(默认为true)
        mAdapter.loadMoreModule?.isEnableLoadMoreIfNotFullPage =false
    }

    /**
     * 重新加载数据
     */
    private fun refresh() {
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        mAdapter.loadMoreModule?.isEnableLoadMore = false
        // 下拉刷新，需要重置页数
        mPageInfo.reset()
        //请求数据
        request()
    }

    private fun request(){
        when(mMode){
            MODE_BRANDID->{
                mPresenter.getGoodList(mBrandId, mPageInfo.page)
            }
            MODE_SEARCH_KEYWORD->{
                mPresenter.getGoodList(mSearchKeyword, mPageInfo.page)
            }
        }
    }

    private fun loadMore(){
        request()
    }

    override fun initBusinessInjection() {
        DaggerGoodListComponent.builder()
            .activityComponent(activityComponent)
            .build()
            .inject(this)
        mPresenter.mView = this
    }

    override fun onGoodListResult(goodPageBean: GoodPageBean) {
        val goods = goodPageBean.goods.toMutableList()
        val pagesize = goodPageBean.pagesize

        mSwipeLayout.setRefreshing(false)
        mAdapter.loadMoreModule?.isEnableLoadMore = true

        if (mPageInfo.isFirstPage()) {
            //如果是加载的第一页数据，用setNew
            mAdapter.setNewData(goods)
        } else {
            //不是第一页，则用add
            mAdapter.addData(goods)
        }

        if (mPageInfo.page+1 >= pagesize) {
            //如果不够一页,显示没有更多数据布局
            mAdapter.loadMoreModule?.loadMoreEnd()
            toast("没有更多数据了")
        } else {
            //页脚显示加载此页完成
            mAdapter.loadMoreModule?.loadMoreComplete()
        }

        // page加一
        mPageInfo.nextPage()
    }
}